<?php
/**
 * 角色模型
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Models;

use App\Traits\Common;
use Illuminate\Support\Facades\Auth;
use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
    //
    use Common;
    protected $table = "roles";
    protected $primaryKey = "id";
    protected $guarded = [];
    public $timestamps = true;

    /**
     * 是否管理员权限
     *
     * @return bool
     */
    public static function isAdmin()
    {
        $roles = env('ADMIN_ROLES', '');
        $admin_roles = explode('|', $roles);
        if (!empty($admin_roles)) {
            //获取用户的所有角色
            $user_roles = Auth::user()->roles;
            foreach ($user_roles as $role) {
                if (in_array($role->id, $admin_roles)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 角色对应的权限
     *
     * @return $this
     */
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'permission_role', 'role_id', 'permission_id')->withPivot(['permission_id', 'role_id']);
    }

    /**
     * 给角色赋予权限
     *
     * @param $permission
     * @return bool
     */
    public function grantPermission($permission)
    {
        return $this->permissions()->save($permission);
    }

    /**
     * 取消角色赋予的权限
     *
     * @param $permission
     * @return mixed
     */
    public function deletePermission($permission)
    {
        return $this->permissions()->detach($permission);
    }

    /**
     * 是否被某个管理员拥有
     */
    public function authorizedByAdmin($admin_id)
    {
        $admin = $this->users->where('id', $admin_id)->first();
        return is_null($admin) ? false : true;
    }
}
